package top.kaoshanji.p1ch05a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Vector;

/**
 * 代码清单-p1ch05a-155页a：随机重定向
 * URL访问地址：/siteSelector
 * @author kaoshanji
 * ^_^
 * create time 2025/4/4 14:57
 */
public class SiteSelector extends HttpServlet {

    Vector sites = new Vector();
    Random random = new Random();

    @Override
    public void init() throws ServletException {

        sites.addElement("https://www.baidu.com/");
        sites.addElement("https://www.huya.com/");
        sites.addElement("https://www.jd.com/");
        sites.addElement("https://time.geekbang.org/");

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());

        int siteIndex = Math.abs(random.nextInt()) % sites.size();
        String site = (String) sites.elementAt(siteIndex);

        // 重定向请求实现的关键
        resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        resp.setHeader("Location", site);

    }

}
